//
//  YDWebView.m
//  YunDongGym
//
//  Created by lqq on 2018/6/8.
//  Copyright © 2018年 lqq. All rights reserved.
//

#import "YDWebView.h"
#import "KKUUID.h"
#import "YDWebViewController.h"
@interface YDWebView ()
@property(nonatomic ,assign) CGFloat lastHeight;

@end

@implementation YDWebView
- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
        [self _config];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self _config];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration {
    self = [super initWithFrame:frame configuration:configuration];
    if (self) {

    }
    return self;
}

- (void)_config {
    self.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal;
    self.bridge = [WKWebViewJavascriptBridge bridgeForWebView:self];
    [self.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
    [self registerNativeFunctions];
    
}
- (void)registerNativeFunctions {
    __weak __typeof (self)weakSelf = self;
     [self.bridge registerHandler:@"handlerHtmlMessage" handler:^(id data, WVJBResponseCallback responseCallback) {
         __strong __typeof (weakSelf) strongSelf = weakSelf;
         NSNumber *typeNum = [data safeObjectForKey:@"type"];
         NSDictionary *obj = [data safeObjectForKey:@"data"];
         HtmlRegistHandleType type = [typeNum integerValue];
         switch (type) {
            case HtmlRegistHandleType_SetTitle:
            {
                if ([strongSelf.YDWebDelegate respondsToSelector:@selector(setControllerTitle:)]) {
                    [strongSelf.YDWebDelegate setControllerTitle:[obj safeObjectForKey:@"title"]];
                }
            }
                 break;
            case HtmlRegistHandleType_OpenH5:
            {
                 NSString *url = [obj safeObjectForKey:@"url"];
                YDWebViewController *webVC = [YDWebViewController controllerWithUrl:url];
                [[strongSelf getCurrentViewController].navigationController pushViewController:webVC animated:YES];
            }
                 break;
            case HtmlRegistHandleType_GetUserInfo:
             {
                 NSDictionary *userInfo = @{@"deviceId":[KKUUID getUUID],@"authorization": SAFE_NIL_STRING(RI.account.token),@"gymId":SAFE_NIL_STRING(RI.currentGym.gymId)};
                 [strongSelf.bridge callHandler:@"setHtml" data:@{@"type":@(HtmlCallHandleType_SetUserInfo),@"data":userInfo}];
             }
                 break;
                 
             default:
                 break;
         }
     }];
}

#pragma mark KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
//    CGSize size = [[change objectForKey:NSKeyValueChangeNewKey] CGSizeValue];
    
    if ([self.YDWebDelegate respondsToSelector:@selector(webView:contentSizeDidChanged:)]) {
        __block CGFloat newHeight = 0;
        [self evaluateJavaScript:@"document.body.scrollHeight;" completionHandler:^(id _Nullable height, NSError * _Nullable error) {
            if (!error) {
                newHeight = [height floatValue];
                if (self.lastHeight != newHeight || newHeight == 0) {
                    self.lastHeight =  newHeight;
                    [self.YDWebDelegate webView:self contentSizeDidChanged:CGSizeMake(kDeviceWidth, newHeight)];
                }
            }
        }];
    }
}



- (void)dealloc
{
    self.YDWebDelegate = nil;
    [self.scrollView removeObserver:self forKeyPath:@"contentSize"];
    NSLog(@"%s",__FUNCTION__);
}

@end
